# coding:UTF-8
import numpy as np
from classify.simple import sig

def load_weight(w):
    '''
    导入LR模型
    :param w:权重所在的文件位置
    :return: 权重的矩阵
    '''
    f = open(w)
    w = []
    for line in f.readlines():
        lines = line.strip().split("\t")
        w_tmp = []
        for x in lines:
            w_tmp.append(float(x))
        w.append(w_tmp)
    f.close()
    return np.mat(w)

def load_data(file_name, n):
    '''
    导入测试数据
    :param file_name:测试集的位置
    :param n: 特征的个数
    :return: 测试集的特征
    '''
    f = open(file_name)
    feature_data = []
    for line in f.readlines():
        feature_tmp = []
        lines = line.strip().split("\t")
        # print lines[2]
        if len(lines) != n - 1:
            continue
        feature_tmp.append(1)
        for x in lines:
            # print x
            feature_tmp.append(float(x))
        feature_data.append(feature_tmp)
    f.close()
    return np.mat(feature_data)

def predict(data, w):
    '''
    对策是数据进行预测
    :param data: 测试数据的特征
    :param w: 模型的参数
    :return:最终预测的结果
    '''
    #获取Sigmoid值
    h = sig(data * w.T)
    m = np.shape(h)[0]
    for i in range(m):
        if h[i, 0] < 0.5:
            h[i, 0] = 0.0
        else:
            h[i, 0] = 1.0
    return h

def save_result(file_name, result):
    '''
    保存最终的测试结果
    :param file_name:预测结果保存的文件名
    :param result: 预测的结果
    '''
    m = np.shape(result)[0]
    #输出预测结果到文件
    tmp = []
    for i in range(m):
        tmp.append(str(result[i, 0]))
    f_result = open(file_name, "w")
    f_result.write("\t".join(tmp))
    f_result.close()

if __name__ == "__main__":
    dir = "/home/xiefeihong/PycharmProjects/SimpleMachineLearning/static/sample/"
    #1. 导入LR模型
    print("------ 1.load model")
    w = load_weight(dir + "weights.txt")
    n = np.shape(w)[1]
    #2. 导入测试数据
    print("------2.load data")
    testData = load_data(dir + "test_data.txt", n)
    #3. 对测试数据进行预测
    print("------3.get prediction")
    h = predict(testData, w)
    #4. 保存最终的预测结果
    print("------4.saveprediction")
    save_result(dir + "result.txt", h)